#include "ImageCacheManager.h"
#include "ImageSaver.h"
#include "ImageLoader.h"
#include <QDebug>
#include <QFileInfo>
#include <QCoreApplication>
#include <QUuid>

ImageCacheManager::ImageCacheManager(QObject *parent) : QObject(parent)
{
    // 不再使用内部的撤销/重做管理器，由ImageManagementPlugin直接管理
}

ImageCacheManager::~ImageCacheManager()
{
    clearCache();
}

QString ImageCacheManager::addImageToCache(const QString &originalImagePath)
{
    // 使用ImageLoader的简化接口直接加载完整的ImageCacheItem
    ImageCacheItem cacheItem = m_imageLoader.loadImageCacheItem(originalImagePath);
    
    // 检查加载是否成功
    if (cacheItem.originalImage.isNull()) {
        qWarning() << "加载图像失败:" << m_imageLoader.errorMessage();
        return QString();
    }

    // 生成唯一GUID
    QString imageGuid = QUuid::createUuid().toString(QUuid::Id128);
    
    // 添加到缓存
    m_imageCache[imageGuid] = cacheItem;
    emit imageAdded(imageGuid);

    return imageGuid;
}

bool ImageCacheManager::addImageToCache(const QString &imageGuid, const QImage &originalImage)
{
    if(m_imageCache.contains(imageGuid))
    {
        m_imageCache[imageGuid].originalImage=originalImage;
        return true;
    }
    ImageCacheItem newItem;
    newItem.originalImage = originalImage;
    newItem.hasProcessedImage = false;
    newItem.originalFilePath.clear();
    newItem.processedFilePath.clear();
    newItem.paramsFilePath.clear();
    newItem.processingParams.clear();
    newItem.axisParams.lengthRatio = 1.0;
    newItem.axisParams.timeRatio = 1.0;
    newItem.axisParams.wavelengthRatio = 1.0;
    newItem.axisParams.lengthUnit = "px";
    newItem.axisParams.timeUnit = "s";
    newItem.axisParams.wavelengthUnit = "nm";
    newItem.axisParams.xAxisUnit = 0;
    newItem.axisParams.yAxisUnit = 0;
    m_imageCache[imageGuid] = newItem;
    emit imageAdded(imageGuid);
    return true;
}

QString ImageCacheManager::addImageToCache(const QImage &originalImage)
{
    ImageCacheItem newItem;
    newItem.originalImage = originalImage;
    newItem.hasProcessedImage = false;
    newItem.originalFilePath.clear();
    newItem.processedFilePath.clear();
    newItem.paramsFilePath.clear();
    newItem.processingParams.clear();
    newItem.axisParams.lengthRatio = 1.0;
    newItem.axisParams.timeRatio = 1.0;
    newItem.axisParams.wavelengthRatio = 1.0;
    newItem.axisParams.lengthUnit = "px";
    newItem.axisParams.timeUnit = "s";
    newItem.axisParams.wavelengthUnit = "nm";
    newItem.axisParams.xAxisUnit = 0;
    newItem.axisParams.yAxisUnit = 0;
    QString imageGuid = QUuid::createUuid().toString();
    m_imageCache[imageGuid] = newItem;
    emit imageAdded(imageGuid);
    return imageGuid;
}

QImage ImageCacheManager::getOriginalImage(const QString &imageGuid) const
{
    if (m_imageCache.contains(imageGuid)) {
        return m_imageCache[imageGuid].originalImage;
    }
    return QImage();
}

QImage ImageCacheManager::getProcessedImage(const QString &imageGuid) const
{
    if (m_imageCache.contains(imageGuid) && m_imageCache[imageGuid].hasProcessedImage) {
        return m_imageCache[imageGuid].processedImage;
    }
    return QImage();
}

QImage ImageCacheManager::getDisplayImage(const QString &imageGuid) const
{
    if (m_imageCache.contains(imageGuid)) {
        const ImageCacheItem &item = m_imageCache[imageGuid];
        if (item.hasProcessedImage) {
            return item.processedImage;
        } else {
            return item.originalImage;
        }
    }
    return QImage();
}

void ImageCacheManager::setProcessedImage(const QString &imageGuid, const QImage &processedImage)
{
    if (m_imageCache.contains(imageGuid)) {
        ImageCacheItem &item = m_imageCache[imageGuid];
        
        // 更新处理后图像
        item.processedImage = processedImage;
        item.hasProcessedImage = !processedImage.isNull();
        
        // 发出更新信号
        emit imageUpdated(imageGuid);
    }
}

void ImageCacheManager::setOriginalImage(const QString &imageGuid, const QImage &originalImage, bool createIfMissing)
{
    if (m_imageCache.contains(imageGuid)) {
        ImageCacheItem &item = m_imageCache[imageGuid];
        item.originalImage = originalImage;
        // 更新标志不影响处理后图像
        emit imageUpdated(imageGuid);
        return;
    }
    
    if (createIfMissing) {
        ImageCacheItem newItem;
        newItem.originalImage = originalImage;
        newItem.hasProcessedImage = false;
        // 默认参数初始化
        newItem.axisParams.lengthRatio = 1.0;
        newItem.axisParams.timeRatio = 1.0;
        newItem.axisParams.wavelengthRatio = 1.0;
        newItem.axisParams.lengthUnit = "px";
        newItem.axisParams.timeUnit = "s";
        newItem.axisParams.wavelengthUnit = "nm";
        newItem.axisParams.xAxisUnit = 0;
        newItem.axisParams.yAxisUnit = 0;
        
        m_imageCache[imageGuid] = newItem;
        emit imageAdded(imageGuid);
    }
}

double ImageCacheManager::getLengthRatio(const QString &imageGuid) const
{
    if (m_imageCache.contains(imageGuid)) {
        return m_imageCache[imageGuid].axisParams.lengthRatio;
    }
    return 1.0;
}

void ImageCacheManager::setLengthRatio(const QString &imageGuid, double ratio)
{
    if (m_imageCache.contains(imageGuid)) {
        ImageCacheItem &item = m_imageCache[imageGuid];
        item.axisParams.lengthRatio = ratio;
        
        // 发出更新信号
        emit imageUpdated(imageGuid);
    }
}

QString ImageCacheManager::getLengthUnit(const QString &imageGuid) const
{
    if (m_imageCache.contains(imageGuid)) {
        return m_imageCache[imageGuid].axisParams.lengthUnit;
    }
    return "px";
}

void ImageCacheManager::setLengthUnit(const QString &imageGuid, const QString &unit)
{
    if (m_imageCache.contains(imageGuid)) {
        ImageCacheItem &item = m_imageCache[imageGuid];
        item.axisParams.lengthUnit = unit;
        
        // 发出更新信号
        emit imageUpdated(imageGuid);
    }
}

double ImageCacheManager::getTimeRatio(const QString &imageGuid) const
{
    if (m_imageCache.contains(imageGuid)) {
        return m_imageCache[imageGuid].axisParams.timeRatio;
    }
    return 1.0;
}

void ImageCacheManager::setTimeRatio(const QString &imageGuid, double ratio)
{
    if (m_imageCache.contains(imageGuid)) {
        ImageCacheItem &item = m_imageCache[imageGuid];
        item.axisParams.timeRatio = ratio;
        
        // 发出更新信号
        emit imageUpdated(imageGuid);
    }
}

QString ImageCacheManager::getTimeUnit(const QString &imageGuid) const
{
    if (m_imageCache.contains(imageGuid)) {
        return m_imageCache[imageGuid].axisParams.timeUnit;
    }
    return "s";
}

void ImageCacheManager::setTimeUnit(const QString &imageGuid, const QString &unit)
{
    if (m_imageCache.contains(imageGuid)) {
        ImageCacheItem &item = m_imageCache[imageGuid];
        item.axisParams.timeUnit = unit;
        
        // 发出更新信号
        emit imageUpdated(imageGuid);
    }
}

double ImageCacheManager::getWavelengthRatio(const QString &imageGuid) const
{
    if (m_imageCache.contains(imageGuid)) {
        return m_imageCache[imageGuid].axisParams.wavelengthRatio;
    }
    return 1.0;
}

void ImageCacheManager::setWavelengthRatio(const QString &imageGuid, double ratio)
{
    if (m_imageCache.contains(imageGuid)) {
        ImageCacheItem &item = m_imageCache[imageGuid];
        item.axisParams.wavelengthRatio = ratio;
        
        // 发出更新信号
        emit imageUpdated(imageGuid);
    }
}

QString ImageCacheManager::getWavelengthUnit(const QString &imageGuid) const
{
    if (m_imageCache.contains(imageGuid)) {
        return m_imageCache[imageGuid].axisParams.wavelengthUnit;
    }
    return "nm";
}

void ImageCacheManager::setWavelengthUnit(const QString &imageGuid, const QString &unit)
{
    if (m_imageCache.contains(imageGuid)) {
        ImageCacheItem &item = m_imageCache[imageGuid];
        item.axisParams.wavelengthUnit = unit;
        
        // 发出更新信号
        emit imageUpdated(imageGuid);
    }
}

int ImageCacheManager::getXAxisUnit(const QString &imageGuid) const
{
    if (m_imageCache.contains(imageGuid)) {
        return m_imageCache[imageGuid].axisParams.xAxisUnit;
    }
    return 0;  // 默认像素单位
}

void ImageCacheManager::setXAxisUnit(const QString &imageGuid, int unit)
{
    if (m_imageCache.contains(imageGuid)) {
        ImageCacheItem &item = m_imageCache[imageGuid];
        item.axisParams.xAxisUnit = unit;
        
        // 发出更新信号
        emit imageUpdated(imageGuid);
    }
}

int ImageCacheManager::getYAxisUnit(const QString &imageGuid) const
{
    if (m_imageCache.contains(imageGuid)) {
        return m_imageCache[imageGuid].axisParams.yAxisUnit;
    }
    return 0;  // 默认像素单位
}

void ImageCacheManager::setYAxisUnit(const QString &imageGuid, int unit)
{
    if (m_imageCache.contains(imageGuid)) {
        ImageCacheItem &item = m_imageCache[imageGuid];
        item.axisParams.yAxisUnit = unit;
        
        // 发出更新信号
        emit imageUpdated(imageGuid);
    }
}



bool ImageCacheManager::removeImageFromCache(const QString &imageGuid)
{
    if (m_imageCache.contains(imageGuid)) {
        m_imageCache.remove(imageGuid);
        emit imageRemoved(imageGuid);
        return true;
    }
    return false;
}

void ImageCacheManager::clearCache()
{
    QStringList guids = getAllImageGuids();
    for (const QString &guid : qAsConst(guids)) {
        m_imageCache.remove(guid);
    }
}

bool ImageCacheManager::containsImage(const QString &imageGuid) const
{
    return m_imageCache.contains(imageGuid);
}

QStringList ImageCacheManager::getAllImageGuids() const
{
    return m_imageCache.keys();
}

void ImageCacheManager::setDefaultSavePath(const QString &path)
{
    m_imageSaver.setDefaultSavePath(path);
}

QString ImageCacheManager::getDefaultSavePath() const
{
    return m_imageSaver.getDefaultSavePath();
}

void ImageCacheManager::setDefaultSaveFormat(const QString &format)
{
    m_imageSaver.setDefaultSaveFormat(format);
}

QString ImageCacheManager::getDefaultSaveFormat() const
{
    return m_imageSaver.getDefaultSaveFormat();
}

bool ImageCacheManager::saveImageWithParams(const QString &imageGuid, const QString &savePath)
{
    if (!m_imageCache.contains(imageGuid)) {
        qWarning() << "图像不在缓存中:" << imageGuid;
        return false;
    }
    
    const ImageCacheItem &item = m_imageCache[imageGuid];
    
    // 准备保存基础路径（不含扩展名）
    QFileInfo saveInfo(savePath);
    QString baseFilePath = saveInfo.absolutePath() + "/" + saveInfo.baseName();
    
    // 使用简化的saveImageCacheItem接口直接保存ImageCacheItem
    // 这个函数会自动处理原始图像、处理后图像和参数文件的保存
    if (!m_imageSaver.saveImageCacheItem(baseFilePath, item)) {
        qWarning() << "无法保存图像缓存项:" << baseFilePath << m_imageSaver.errorMessage();
        return false;
    }
    
    return true;
}





int ImageCacheManager::addProcessingParam(const QString &imageGuid, const QVariantMap &params, bool enableUndo) {
    if (!m_imageCache.contains(imageGuid)) {
        return -1;
    }
    
    // 检查参数是否包含algorithmName
    if (!params.contains("algorithmName")) {
        qWarning() << "处理参数必须包含algorithmName字段";
        return -1;
    }
    
    ImageCacheItem &item = m_imageCache[imageGuid];
    
    // 添加参数到列表
    item.processingParams.append(params);
    
    // 获取添加的索引位置
    int index = item.processingParams.size() - 1;
    
    // 检查所有图像处理参数是否都未处理
    bool allNotProcessed = true;
    for (const QVariantMap &param : item.processingParams) {
        // 检查参数是否包含processed=true
        if (param.contains("processed") && param["processed"].toBool()) {
            allNotProcessed = false;
            break;
        }
    }
    
    // 如果所有算法都未处理，则释放处理后的图像
    if (allNotProcessed) {
        item.processedImage = QImage();
        item.hasProcessedImage = false;
    }
    
    emit imageUpdated(imageGuid);
    return index;
}

bool ImageCacheManager::removeProcessingParam(const QString &imageGuid, int index, bool enableUndo) {
    if (!m_imageCache.contains(imageGuid)) {
        return false;
    }
    
    ImageCacheItem &item = m_imageCache[imageGuid];
    
    // 检查索引是否有效
    if (index < 0 || index >= item.processingParams.size()) {
        qWarning() << "参数索引无效";
        return false;
    }
    
    // 移除参数
    item.processingParams.removeAt(index);
    
    // 检查所有图像处理参数是否都未处理
    bool allNotProcessed = true;
    for (const QVariantMap &param : item.processingParams) {
        // 检查参数是否包含processed=true
        if (param.contains("processed") && param["processed"].toBool()) {
            allNotProcessed = false;
            break;
        }
    }
    
    // 如果所有算法都未处理，则释放处理后的图像
    if (allNotProcessed) {
        item.processedImage = QImage();
        item.hasProcessedImage = false;
    }
    
    emit imageUpdated(imageGuid);
    return true;
}

void ImageCacheManager::clearProcessingParams(const QString &imageGuid, bool enableUndo) {
    if (!m_imageCache.contains(imageGuid)) {
        return;
    }
    
    ImageCacheItem &item = m_imageCache[imageGuid];
    
    // 清除所有处理参数
    item.processingParams.clear();
    
    // 释放处理后的图像
    item.processedImage = QImage();
    item.hasProcessedImage = false;
    
    emit imageUpdated(imageGuid);
}

QList<QVariantMap> ImageCacheManager::getAllProcessingParams(const QString &imageGuid) const {
    if (!m_imageCache.contains(imageGuid)) {
        return QList<QVariantMap>();
    }
    
    return m_imageCache[imageGuid].processingParams;
}

QVariantMap ImageCacheManager::getProcessingParam(const QString &imageGuid, int index) const {
    if (!m_imageCache.contains(imageGuid)) {
        return QVariantMap();
    }
    
    const ImageCacheItem &item = m_imageCache[imageGuid];
    
    // 检查索引是否有效
    if (index < 0 || index >= item.processingParams.size()) {
        qWarning() << "参数索引无效";
        return QVariantMap();
    }
    
    return item.processingParams.at(index);
}
